import React, { memo } from "react";
import { useHistory } from "react-router-dom";
import { useDispatch, useSelector, shallowEqual } from "react-redux";
import { PostArticleWrapper } from "./style";
import { Input, Button, message } from "antd";
import { useState, useEffect, useRef, useCallback } from "react";
import storage from "@/utils/storage";
import { isToken } from "@/hooks";
import { pubMomment, saveMommentPicture } from "@/service/discover";
import UploadImg from "../upload";
import { ReactEmojiEditor } from "react-emotor";
const { TextArea } = Input;

export default memo(function PostArticle(props) {
  const { userDetail, setPage, setPictureInfo, pictureInfo, category_id } =
    props;
  const [isFocus, setisFocus] = useState(true);
  const [content, setcontent] = useState("");
  const [textValue, settextValue] = useState("");
  const [isRefresh, setisRefresh] = useState(false);
  const textarea = useRef();
  const history = useHistory();
  const { state } = props;

  const change = (e) => {
    setcontent(e.target.value);
  };

  const submit = async () => {
    let token = await isToken();
    if (!token) {
      history.push("/login");
      return;
    }
    let obj = {
      content: content,
      user_id: userDetail.id,
      user_name: userDetail.nick,
      avatar: userDetail.avatarUrl,
      category_id,
    };

    const res = await pubMomment(obj);
    let moment_id = res.data.insertId;
    if (res.data) {
      setcontent("");
    }

    for (const list of pictureInfo) {
      let obj = {
        moment_id,
        filename: list,
      };
      await saveMommentPicture(obj);
    }

    message.success("瞬间发布成功!");
    state();
    setisRefresh(true);
    setPage(1);
  };

  const updataRefreshState = () => {
    setisRefresh(false);
  };
  return (
    <PostArticleWrapper>
      <TextArea
        showCount={true}
        ref={textarea}
        bordered={false}
        allowClear={true}
        maxLength={2000}
        placeholder={
          userDetail.nick
            ? "Hi " + userDetail.nick + "! 快来和我分享新鲜事吧!"
            : "您还未登录,快去登录!"
        }
        className="textarea"
        rows={4}
        value={content}
        onChange={(e) => change(e)}
      />
      <UploadImg
        updataRefreshState={updataRefreshState}
        isRefresh={isRefresh}
        setPictureInfo={setPictureInfo}
      ></UploadImg>
      <div className="release_box">
        <Button
          disabled={content.trim().length == 0}
          className="release_btn"
          type="primary"
          size="middle"
          onClick={() => submit()}
        >
          发布瞬间
        </Button>
      </div>
    </PostArticleWrapper>
  );
});
